<template>
  <div class="travel-info-container">
    <!-- 景区详情区域 -->
    <div class="scenic-detail">
      <el-card>
        <div class="image-area">
          <el-carousel height="350px">
            <!-- <el-carousel-item v-for="image in scenicInfo.imgUrl" :key="image">
              <img :src="image" class="scenic-image">
            </el-carousel-item> -->
            <el-carousel-item>
              <img :src="scenicInfo.imgUrl" class="scenic-image">
            </el-carousel-item>
          </el-carousel>
        </div>
        <div class="info-area">
          <h2>{{ scenicInfo.name }}</h2>
          <div class="address">
            <i class="el-icon-location"></i>
            <span>{{ scenicInfo.addressDetail }}</span>
          </div>
          <div class="description">{{ scenicInfo.info }}</div>
          <div class="price-area">
            <span class="price">{{ scenicInfo.ticketPrice === 0 ? '免费' : '¥'+scenicInfo.ticketPrice }}</span>
            <el-button type="primary" @click="showPayDialog(scenicInfo.id)">立即预订</el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 最近订票区域 -->
    <div class="recent-bookings" v-if="scenicInfo.ticketPrice != 0" >
      <h3>最近订票</h3>
      <el-scrollbar height="120px">
        <div class="booking-list">
          <div v-for="booking in recentBookings" :key="booking.id" class="booking-item">
            <el-avatar :size="30" :src="booking.avatar"></el-avatar>
            <span class="booking-user">{{ booking.username }}</span>
            <span class="booking-time">{{ booking.time }}</span>
            <span class="booking-price">¥{{ booking.price }}</span>
          </div>
        </div>
      </el-scrollbar>
    </div>

    <!-- 评论区域 -->
    <div class="comment-section">
      <h3>游客评论</h3>
      <!-- 发表评论 -->
      <div class="comment-input">
        <el-input
          v-model="newComment"
          type="textarea"
          :rows="3"
          placeholder="分享您的游览体验..."
        ></el-input>
        <el-button type="primary" @click="submitComment" class="submit-btn">发表评论</el-button>
      </div>
      
      <!-- 评论列表 -->
      <div class="comment-list" v-if="comments.length > 0">
        <div v-for="comment in comments" :key="comment.id" class="comment-item">
          <div class="comment-user">
            <el-avatar :size="40" :src="comment.avatar === '' || comment.avatar === null ? require('@/assets/default_img.jpg') : comment.avatar"></el-avatar>
            <span class="username">{{ comment.username }}</span>
            <span class="time">{{ comment.createTime }}</span>
          </div>
          <div class="comment-content">{{ comment.content }}</div>
          <div class="comment-actions" style="display: flex; justify-content: flex-end;">
            <el-button 
              type="text"
              @click="handleLike(comment)"
              :class="{'is-liked': comment.isLiked}"
            >
              <el-icon :size="20"  :color="comment.isLiked ? '#409EFF' : '#909399'">
                <Star />
              </el-icon>
            </el-button>
            <el-text style="margin-left: 4px" class="mx-1" type="primary">{{ comment.like }}</el-text>
          </div>
        </div>
      </div>

      <div class="comment-list" v-else>
        <el-empty description="评论区是空的，快来留言吧😀！" />
      </div>
      
    </div>

    <!-- 支付弹窗 -->
    <el-dialog
      title="订单支付"
      v-model="payDialogVisible"
      width="30%">
      <div class="alipay-style-dialog">
        <div class="alipay-header">
          <img src="https://img.alicdn.com/imgextra/i1/O1CN01R0YN9T1nN1BCkqP5Y_!!6000000005072-2-tps-140-140.png" class="alipay-logo">
          <span class="alipay-title">支付宝</span>
        </div>
        <div class="order-details">
          <div class="order-info">
            <p class="order-name">{{ scenicInfo.name }} - 景区门票</p>
            <p class="order-number">订单编号：{{ orderId }}</p>
          </div>
          <div class="order-price">
            <span class="price-symbol">¥</span>
            <span class="price-value">{{ scenicInfo.ticketPrice === 0 ? '0.00' : scenicInfo.ticketPrice.toFixed(2) }}</span>
          </div>
        </div>
        <div class="payment-methods">
          <div class="payment-method-title">支付方式</div>
          <div class="payment-method-item" :class="{ selected: payMethod === 'alipay' }" @click="selectPayMethod('alipay')">
            <div class="method-icon alipay-icon"></div>
            <div class="method-name">支付宝</div>
            <div class="method-check" :class="{ active: payMethod === 'alipay' }"></div>
          </div>
          <div class="payment-method-item" :class="{ selected: payMethod === 'wechat' }" @click="selectPayMethod('wechat')">
            <div class="method-icon wechat-icon"></div>
            <div class="method-name">微信支付</div>
            <div class="method-check" :class="{ active: payMethod === 'wechat' }"></div>
          </div>
        </div>
        <div class="alipay-qrcode">
          <div class="qrcode-container">
            <img style="width: 180px;height: 180px;" :src="require('../assets/vx_pay_code.jpg')" alt="支付二维码">
          </div>
          <p class="qrcode-tip">请使用{{ payMethod === 'alipay' ? '支付宝' : '微信' }}扫一扫</p>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="payDialogVisible = false">取消支付</el-button>
          <el-button type="primary" @click="handlePay">支付完成</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive,onMounted, } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'
import axios from 'axios'
export default {
  setup() {
    
    onMounted(() => {
      const route = useRoute()
      const travelId = route.params.id;
      axios.get('/api/scenic/'+travelId)
      .then(res => {
        if(res.data.code === 200){
          scenicInfo.id = res.data.data.id
          scenicInfo.name = res.data.data.name
          scenicInfo.addressDetail = res.data.data.addressDetail
          scenicInfo.info = res.data.data.info
          scenicInfo.ticketPrice = res.data.data.ticketPrice
          scenicInfo.imgUrl = res.data.data.imgUrl
        }else{
          ElMessage({
            message: res.data.message,
            type: 'error',
          })
        }
      }).catch(err => {
        ElMessage({
          message: "获取数据失败!",
          type: 'error',
        })
      })
      getAllComments(travelId)
      scenicView(travelId)
    })

    const scenicView = (travelId) => {
      console.log(travelId)
      axios.post('/api/scenic/view',{
        id: travelId,
        userId: 1
      })
      .then(res => {
        if(res.data.code === 200){
          console.log("浏览量+1")
        }
      })
    }

    const scenicInfo = reactive({
      id: '',
      name: '西湖风景区',
      addressDetail: '浙江省杭州市西湖区',
      info: '西湖风景秀丽，湖光山色，令人陶醉。四季景色各不相同，春有花港观鱼，夏有荷风送香，秋有平湖秋月，冬有断桥残雪。',
      ticketPrice: 80,
      imgUrl: 'https://example.com/xihu.jpg'
    })

    const payDialogVisible = ref(false)
    const newComment = ref('')
    const comments = ref([])
    const payMethod = ref('wechat') // 默认选中微信支付
    const orderId = ref('')

    const getAllComments = (travelId) => {
      axios.get('/api/scenic/comment/all/'+travelId)
      .then(res => {
        if(res.data.code === 200){
          console.log(res.data.data)
          comments.value = res.data.data
        }else{
          ElMessage({
            message: res.data.message,
            type: 'error',
          })
        }
      }).catch(err => {
        ElMessage.error('获取评论区失败')
      })
    }

    const showPayDialog = (id) => {

      if(id === ''){
        ElMessage.warning('请先选择景区')
        return
      }

      if(scenicInfo.ticketPrice === 0){
        ElMessage({
            message: "该景区是免费的直接前往即可",
            type: 'success',
          })
        return
      }else{
        const user = checkLogin()
        if(user === '') {
          return
        }
        //创建订单获取订单号
        axios.post('/api/ticket/order',{
          userId: user.id,
          scenicId: id,
        })
        .then(res => {
          if(res.data.code === 200){
            const orderNumber = res.data.data
            orderId.value = orderNumber
            ElMessage.success("订单创建成功！您的单号："+orderNumber)
            payDialogVisible.value = true
          }
        })
        .catch(err => {
          ElMessage.error(err.response.data.message)
        })
      }
    }

    const handlePay = () => {
      const user = checkLogin()
      if(user === '') {
        return
      }
      ElMessage.success('支付成功！')
      payDialogVisible.value = false
    }

    // 发表评论
    const submitComment = () => {
      const user = checkLogin()
      if(user === '') {
        return
      }

      if (!newComment.value.trim()) {
        ElMessage.warning('请输入评论内容')
        return
      }
      
      const commentData = {
        scenicId: scenicInfo.id,
        content: newComment.value,
        userId: user.id
      }

      axios.post('/api/scenic/comment',commentData)
      .then(res => {
        if(res.data.code === 200){
          ElMessage.success('评论发表成功')
          const comment = res.data.data
          comments.value.unshift({
            id: comment.id,
            username: comment.username,
            avatar: comment.avatar,
            content: newComment.value,
            createTime: comment.createTime,
            like: 0,
            isLiked: comment.isLiked
          })
          newComment.value = ''
        }else{
          ElMessage.error('评论发表失败')
        }
      })
      .catch(err => {
        ElMessage.error('评论发表失败')
      })
    }

    const handleLike = (comment) => {
      const user = checkLogin()
      if(user === '') {
        return
      }

      if (!comment.isLiked) {
        //点赞
        axios.post('/api/scenic/comment/like',{
          commentId: comment.id,
          userId: user.id
        })
        .then(res => {
          if(res.data.code === 200){
            comment.like++
            comment.isLiked = true
            ElMessage.success('点赞成功')
          }else{
            ElMessage.error(res.data.message)
          }
        }).catch(err => {
          ElMessage.error('点赞失败')
        })
      } else {  
        //取消点赞
        axios.post('/api/scenic/comment/like/cancel',{
          commentId: comment.id,
          userId: 1
        })
        .then(res => {
          if(res.data.code === 200){
            comment.like--
            comment.isLiked = false
            ElMessage.info('取消点赞')
          }else{
            ElMessage.error(res.data.message)
          }
        }).catch(err => {
          ElMessage.error('取消失败')
        })
      }
    }

    const checkLogin = () => {
      const user = JSON.parse(sessionStorage.getItem('userInfo'))
      if(user === null || user === undefined || user === '') {
        ElMessage.error('请先登录')
        return ''
      }
      return user
    }

    // 选择支付方式
    const selectPayMethod = (method) => {
      payMethod.value = method
    }

    return {
      scenicInfo,
      payDialogVisible,
      newComment,
      comments,
      showPayDialog,
      handlePay,
      submitComment,
      handleLike,
      scenicView,
      checkLogin,
      payMethod,
      selectPayMethod,
      orderId
    }
  }
}
</script>

<style scoped>
.travel-info-container {
  padding: 20px;
}

.scenic-detail {
  margin-bottom: 30px;
}

.image-area {
  margin-bottom: 20px;
}

.scenic-image {
  width: 100%;
  height: 400px;
  object-fit: cover;
}

.info-area {
  padding: 20px;
}

.address {
  color: #666;
  margin: 10px 0;
}

.description {
  margin: 20px 0;
  line-height: 1.6;
}

.price-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  color: #f56c6c;
  font-size: 24px;
  font-weight: bold;
}

.comment-section {
  margin-top: 30px;
}

.comment-input {
  margin: 20px 0;
}

.submit-btn {
  margin-top: 10px;
  float: right;
}

.comment-item {
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.comment-user {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.username {
  margin-left: 10px;
  font-weight: bold;
}

.time {
  margin-left: 20px;
  color: #999;
  font-size: 12px;
}

.comment-content {
  margin: 10px 0;
  line-height: 1.6;
}

.comment-actions {
  margin-top: 10px;
}

.like {
  cursor: pointer;
  color: #666;
}

.like .is-liked {
  color: #409eff;
}

.pay-dialog-content {
  text-align: center;
}

.qr-code {
  margin: 20px 0;
}

.qr-code img {
  width: 200px;
  height: 200px;
}

.alipay-style-dialog {
  padding: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.alipay-header {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 20px;
}

.alipay-logo {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}

.alipay-title {
  font-size: 18px;
  font-weight: bold;
  color: #00a0e9;
}

.order-details {
  background-color: #f8f8f8;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
}

.order-info {
  margin-bottom: 10px;
}

.order-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.order-number {
  font-size: 12px;
  color: #999;
}

.order-price {
  text-align: center;
  margin: 15px 0;
}

.price-symbol {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.price-value {
  font-size: 30px;
  font-weight: bold;
  color: #333;
}

.payment-methods {
  margin-bottom: 20px;
}

.payment-method-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.payment-method-item {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  cursor: pointer;
  margin-bottom: 10px;
}

.payment-method-item.selected {
  border-color: #00a0e9;
  background-color: #f7fcff;
}

.method-icon {
  width: 24px;
  height: 24px;
  background-position: center;
  background-repeat: no-repeat;
  background-size: contain;
  margin-right: 10px;
}

.alipay-icon {
  background-image: url(https://img.alicdn.com/imgextra/i1/O1CN01R0YN9T1nN1BCkqP5Y_!!6000000005072-2-tps-140-140.png);
}

.wechat-icon {
  background-image: url(https://res.wx.qq.com/a/wx_fed/assets/res/NTI4MWU5.ico);
}

.method-name {
  flex: 1;
  font-size: 14px;
}

.method-check {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  border: 1px solid #00a0e9;
  position: relative;
}

.method-check.active::after {
  content: '';
  position: absolute;
  width: 8px;
  height: 8px;
  background-color: #00a0e9;
  border-radius: 50%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.alipay-qrcode {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 20px 0;
}

.qrcode-container {
  padding: 10px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  margin-bottom: 10px;
}

.qrcode-tip {
  font-size: 14px;
  color: #666;
}
</style>